<template>
  <view class="container">
    <!-- 状态栏占位 -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 商家信息区域 -->
    <view class="merchant-info-section">
      <view class="merchant-info">
        <image 
          class="avatar" 
          :src="userStore.isLoggedIn ? (BASE_URL+userStore.userInfo.avatar || '/static/merchant-placeholder.png') : '/static/merchant-placeholder.png'" 
          mode="aspectFill"
        ></image>
        <view class="merchant-detail">
          <!-- 已登录显示商家信息 -->
          <template v-if="userStore.isLoggedIn && userStore.isMerchant()">
            <view class="merchant-name">{{ userStore.userInfo.shopName || '我的店铺' }}</view>
            <view class="merchant-id">{{ userStore.userInfo.phone ? `联系电话: ${maskPhone(userStore.userInfo.phone)}` : `商家ID: ${userStore.userInfo.id}` }}</view>
          </template>
          <!-- 未登录或非商家显示登录按钮 -->
          <template v-else>
            <view class="login-btn" @click="handleLogin">商家登录</view>
            <view class="merchant-desc">登录后管理您的店铺</view>
          </template>
        </view>
      </view>
      <view class="merchant-stats">
        <view class="stat-item">
          <text class="stat-num">{{ merchantData.orderCount }}</text>
          <text class="stat-label">订单数</text>
        </view>
        <view class="stat-item">
          <text class="stat-num">{{ merchantData.productCount }}</text>
          <text class="stat-label">商品数</text>
        </view>
        <view class="stat-item">
          <text class="stat-num">{{ merchantData.revenue }}</text>
          <text class="stat-label">收入(元)</text>
        </view>
      </view>
    </view>
       
    <!-- 订单管理 -->
    <view class="order-section">
      <view class="section-header">
        <text class="section-title">订单管理</text>
        <view class="view-all" @click="viewAllOrders">
          <text>查看全部</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
      <view class="order-types">
        <view class="order-type-item" @click="viewOrderByType('new')">
          <uni-icons type="notification" size="28" color="#FF8C42"></uni-icons>
          <text>新订单</text>
          <view v-if="merchantData.newOrderCount > 0" class="badge">{{ merchantData.newOrderCount }}</view>
        </view>
        <view class="order-type-item" @click="viewOrderByType('processing')">
          <uni-icons type="spinner" size="28" color="#FF8C42"></uni-icons>
          <text>处理中</text>
        </view>
        <view class="order-type-item" @click="viewOrderByType('shipping')">
          <uni-icons type="car" size="28" color="#FF8C42"></uni-icons>
          <text>配送中</text>
        </view>
        <view class="order-type-item" @click="viewOrderByType('completed')">
          <uni-icons type="checkbox-filled" size="28" color="#FF8C42"></uni-icons>
          <text>已完成</text>
        </view>
        <view class="order-type-item" @click="viewOrderByType('refund')">
          <uni-icons type="refresh" size="28" color="#FF8C42"></uni-icons>
          <text>退款/售后</text>
        </view>
      </view>
    </view>
       
    <!-- 店铺管理 -->
    <view class="service-section">
      <view class="section-header">
        <text class="section-title">店铺管理</text>
      </view>
      <view class="service-grid">
        <view class="service-item" @click="goToService('products')">
          <uni-icons type="shop" size="24" color="#FF8C42"></uni-icons>
          <text>商品管理</text>
        </view>
        <view class="service-item" @click="goToService('promotion')">
          <uni-icons type="gift" size="24" color="#FF8C42"></uni-icons>
          <text>促销活动</text>
        </view>
        <view class="service-item" @click="goToService('finance')">
          <uni-icons type="wallet" size="24" color="#FF8C42"></uni-icons>
          <text>财务管理</text>
        </view>
        <view class="service-item" @click="goToService('comments')">
          <uni-icons type="chat" size="24" color="#FF8C42"></uni-icons>
          <text>评价管理</text>
        </view>
        <view class="service-item" @click="goToService('statistics')">
          <uni-icons type="chart" size="24" color="#FF8C42"></uni-icons>
          <text>数据统计</text>
        </view>
        <view class="service-item" @click="goToService('settings')">
          <uni-icons type="gear" size="24" color="#FF8C42"></uni-icons>
          <text>店铺设置</text>
        </view>
      </view>
    </view>
    
    <!-- 商家工具 -->
    <view class="service-section">
      <view class="section-header">
        <text class="section-title">商家工具</text>
      </view>
      <view class="service-grid">
        <view class="service-item" @click="goToService('printer')">
          <uni-icons type="paperclip" size="24" color="#FF8C42"></uni-icons>
          <text>打印机</text>
        </view>
        <view class="service-item" @click="goToService('delivery')">
          <uni-icons type="map" size="24" color="#FF8C42"></uni-icons>
          <text>配送设置</text>
        </view>
        <view class="service-item" @click="goToService('customer')">
          <uni-icons type="headphones" size="24" color="#FF8C42"></uni-icons>
          <text>客服中心</text>
        </view>
        <view class="service-item" @click="goToService('feedback')">
          <uni-icons type="help" size="24" color="#FF8C42"></uni-icons>
          <text>意见反馈</text>
        </view>
        <view class="service-item" @click="goToService('about')">
          <uni-icons type="info" size="24" color="#FF8C42"></uni-icons>
          <text>关于我们</text>
        </view>
        <view class="service-item" @click="goToService('help')">
          <uni-icons type="help-filled" size="24" color="#FF8C42"></uni-icons>
          <text>帮助中心</text>
        </view>
      </view>
    </view>
    
    <!-- 退出登录按钮 (仅在登录状态显示) -->
    <view v-if="userStore.isLoggedIn && userStore.isMerchant()" class="logout-section">
      <button class="logout-btn" @click="handleLogout">退出登录</button>
    </view>
    
    <!-- 登录弹窗 -->
    <login-popup ref="loginPopupRef"></login-popup>
    
    <!-- 用户类型管理 -->
    <user-type-manager></user-type-manager>
    
    <!-- 底部导航栏 -->
    <tab-bar :active="2"></tab-bar>
  </view>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useUserStore } from '@/store/user';
import UserTypeManager from '@/components/user-type-manager.vue';
import TabBar from '@/components/tab-bar.vue';
import LoginPopup from '@/components/login-popup.vue';
import { BASE_URL } from '@/config/env';

const userStore = useUserStore();
const statusBarHeight = ref(0);
const loginPopupRef = ref(null);

// 商家静态数据
const merchantData = reactive({
  orderCount: 128,
  productCount: 36,
  revenue: 9876.50,
  newOrderCount: 5
});

// 获取状态栏高度
const getStatusBarHeight = () => {
  let systemInfo = null;
  try {
    systemInfo = uni.getSystemInfoSync();
    statusBarHeight.value = systemInfo.statusBarHeight || 0;
    console.log('状态栏高度:', statusBarHeight.value);
  } catch (e) {
    console.error('获取系统信息失败:', e);
    statusBarHeight.value = 0;
  }
};

// 手机号码脱敏
const maskPhone = (phone) => {
  if (!phone || phone.length < 11) return phone;
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};

// 处理登录点击
const handleLogin = () => {
  console.log('商家点击登录按钮');
  if (loginPopupRef.value) {
    // 设置登录类型为商家
    loginPopupRef.value.setLoginType('merchant');
    loginPopupRef.value.open();
  } else {
    console.error('登录弹窗组件未找到');
    uni.showToast({
      title: '登录功能暂不可用',
      icon: 'none'
    });
  }
};

// 处理退出登录
const handleLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确认退出登录？',
    success: (res) => {
      if (res.confirm) {
        userStore.logout();
        uni.showToast({
          title: '已退出登录',
          icon: 'success'
        });
        
        // 退出后跳转到用户首页
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/index/index'
          });
        }, 500);
      }
    }
  });
};

// 查看全部订单
const viewAllOrders = () => {
  // 检查是否登录且是商家
  if (!userStore.isLoggedIn || !userStore.isMerchant()) {
    handleLogin();
    return;
  }
  
  uni.showToast({
    title: '订单管理功能开发中',
    icon: 'none'
  });
};

// 按类型查看订单
const viewOrderByType = (type) => {
  // 检查是否登录且是商家
  if (!userStore.isLoggedIn || !userStore.isMerchant()) {
    handleLogin();
    return;
  }
  
  const typeNames = {
    new: '新订单',
    processing: '处理中订单',
    shipping: '配送中订单',
    completed: '已完成订单',
    refund: '退款/售后'
  };
  
  uni.showToast({
    title: `${typeNames[type] || type}管理功能开发中`,
    icon: 'none'
  });
};

// 跳转到服务页面
const goToService = (service) => {
  // 所有商家服务都需要登录
  if (!userStore.isLoggedIn || !userStore.isMerchant()) {
    handleLogin();
    return;
  }
  
  const serviceNames = {
    products: '商品管理',
    promotion: '促销活动',
    finance: '财务管理',
    comments: '评价管理',
    statistics: '数据统计',
    settings: '店铺设置',
    printer: '打印机设置',
    delivery: '配送设置',
    customer: '客服中心',
    feedback: '意见反馈',
    about: '关于我们',
    help: '帮助中心'
  };
  
  uni.showToast({
    title: `${serviceNames[service] || service}功能开发中`,
    icon: 'none'
  });
};

// 页面加载时执行
onMounted(() => {
  console.log('商家中心页面加载完成');
  // 初始化用户状态
  userStore.initUserState();
  // 获取状态栏高度
  getStatusBarHeight();
  
  // 如果用户已登录但不是商家，提示切换身份
  if (userStore.isLoggedIn && !userStore.isMerchant()) {
    uni.showModal({
      title: '提示',
      content: '您当前是普通用户身份，是否切换为商家身份？',
      success: (res) => {
        if (res.confirm) {
          // 这里可以添加切换身份的逻辑
          // 示例：模拟商家登录
          const merchantInfo = {
            id: 'M' + Math.floor(Math.random() * 10000),
            shopName: '示例商家店铺',
            phone: '13800138000',
            avatar: '/static/merchant-avatar.png'
          };
          userStore.login('merchant', merchantInfo);
        } else {
          // 用户取消，返回用户首页
          uni.reLaunch({
            url: '/pages/index/index'
          });
        }
      }
    });
  }
});
</script>

<style>
.container {
  padding-bottom: 100rpx;
  background-color: #FFF9F2;
}

.merchant-info-section {
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  padding: 40rpx 30rpx;
  color: #fff;
  border-radius: 0 0 30rpx 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 140, 66, 0.2);
}

.merchant-info {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  background-color: #fff;
  margin-right: 30rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}

.login-btn {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.merchant-desc {
  font-size: 24rpx;
  opacity: 0.8;
}

.merchant-stats {
  display: flex;
  justify-content: space-around;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 16rpx;
  padding: 20rpx 0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-num {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 6rpx;
}

.stat-label {
  font-size: 24rpx;
}

.order-section, .service-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #FFE6CC;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  position: relative;
  padding-left: 20rpx;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 30rpx;
  background-color: #FF8C42;
  border-radius: 3rpx;
}

.view-all {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #999;
}

.order-types {
  display: flex;
  padding: 30rpx 0;
}

.order-type-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: transform 0.3s ease;
  position: relative;
}

.order-type-item:active {
  transform: scale(0.95);
}

.order-type-item text {
  font-size: 24rpx;
  margin-top: 10rpx;
  color: #666;
}

.badge {
  position: absolute;
  top: -5rpx;
  right: 20rpx;
  background-color: #FF4D4F;
  color: white;
  font-size: 20rpx;
  min-width: 32rpx;
  height: 32rpx;
  line-height: 32rpx;
  text-align: center;
  border-radius: 16rpx;
  padding: 0 6rpx;
}

.service-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0;
}

.service-item {
  width: 33.33%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
  transition: transform 0.3s ease;
}

.service-item:active {
  transform: scale(0.95);
}

.service-item text {
  font-size: 24rpx;
  margin-top: 10rpx;
  color: #666;
}

.merchant-name {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.merchant-id {
  font-size: 24rpx;
  opacity: 0.8;
}

/* 退出登录按钮 */
.logout-section {
  padding: 30rpx 20rpx;
}

.logout-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
  color: #FF8C42;
  background-color: #fff;
  border: 1rpx solid #FF8C42;
  border-radius: 40rpx;
  transition: all 0.3s ease;
}

.logout-btn:active {
  background-color: #FFF0E0;
}
</style>